package com.chif.demo.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
/**
 * 发送同步消息
 */
public class SyncProducer {

    public static void main(String[] args) throws Exception {
        //创建一个producer，参数为Producer Group名称
        DefaultMQProducer producer = new DefaultMQProducer("pg");

        producer.setNamesrvAddr("192.168.10.100:9876");

        //若为全局有序，设置队列数量
        //producer.setDefaultTopicQueueNums(1);

        //设置最大重试次数，默认2
        producer.setRetryTimesWhenSendFailed(3);

        //设置发送超时时限为5s，默认3s
        producer.setSendMsgTimeout(5000);

        //开启生产者
        producer.start();

        for (int i = 0; i < 100; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message msg = new Message("someTopic", "someTag", body);
            //为消息指定key
            msg.setKeys("key-"+i);

            //发送消息
            /*
            *   SendResult
                SEND_OK,
                FLUSH_DISK_TIMEOUT, 同步刷盘超时
                FLUSH_SLAVE_TIMEOUT, slave同步复制超时
                SLAVE_NOT_AVAILABLE, 没有可用的slave，同步复制
            * */
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }

        //关闭producer
        producer.shutdown();

    }
}
